<template>
	<div class="messages-container" ref="messagesContainer">
		<div
			v-for="(message, index) in props.messageList"
			:key="index"
			:class="[
        'message-bubble',
        message.speaker === 1 ? 'user' :
        message.speaker === 2 ? 'system' : 'script'
      ]"
		>
			<div class="message-avatar" v-if="message.speaker !== 3">
				<a-avatar
					:size="32"
					:style="avatarStyle(message.speaker)"
				>
					{{ message.speaker === 1 ? '客户' : '坐席' }}
				</a-avatar>
			</div>
			<div class="message-content">
				<div class="message-meta" v-if="message.speaker !== 3">
					<span class="message-role">{{ message.speaker === 1 ? '客户' : '坐席' }}</span>
					<span class="message-time" v-if="message.chatTime">{{ formatTime(message.chatTime) }}</span>
				</div>
				<div class="message-text">
					{{ message.content }}
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>

const props = defineProps({
	messageList: Array
});

const avatarStyle = (role) => ({
	backgroundColor: role === 1 ? '#1890ff' : '#00b96b'
});

const formatTime = (timestamp) => {
	return new Date(timestamp).toLocaleTimeString();
};
</script>

<style scoped lang="less">
@user-color: #1677ff;
@system-color: #00b96b;
@script-color: rgba(22, 119, 255, 0.1);

.messages-container {
	min-height: 100px;
	max-height: 700px;
	padding: 16px;
	overflow-y: auto;
	background-color: #fafafa;
	scroll-behavior: smooth;

	.message-bubble {
		display: flex;
		margin-bottom: 16px;
		gap: 12px;

		&.user {
			flex-direction: row;

			.message-text {
				background: @user-color;
				color: white;
				border-radius: 0 12px 12px 12px;
			}
		}

		&.script {
			justify-content: center;
			margin: 12px auto;

			.message-text {
				background: @script-color;
				color: #666;
				border-radius: 12px;
				padding: 3px 10px;
				border: 1px solid rgba(22, 119, 255, 0.2);
			}

			.message-avatar,
			.message-meta {
				display: none;
			}
		}

		&.system {
			flex-direction: row-reverse;

			.message-meta {
				justify-content: flex-end;
			}

			.message-text {
				background: white;
				color: #333;
				border-radius: 12px 0 12px 12px;
				box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
			}
		}

		.message-avatar {
			flex-shrink: 0;
			align-self: flex-end;
		}

		.message-content {
			display: flex;
			flex-direction: column;
			max-width: 80%;
			gap: 4px;
		}

		.message-meta {
			font-size: 12px;
			color: #666;
			display: flex;
			gap: 8px;

			.message-role {
				font-weight: 500;
			}

			.message-time {
				opacity: 0.7;
			}
		}

		.message-text {
			padding: 10px 14px;
			line-height: 1.5;
			word-break: break-word;
			white-space: pre-line;
		}
	}
}
</style>
